package com.travel.sso.service.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.travel.common.pojo.User;
import com.travel.common.redis.JedisClient;
import com.travel.common.util.JsonUtil;
import com.travel.common.util.TravelResult;
import com.travel.sso.dao.UserDAO;
import com.travel.sso.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDAO userDAO;

    @Override
    public TravelResult doRegist(String email, String password) {
        User user = userDAO.getUserEmail(email);
        if (user != null) {
            return TravelResult.getErrorResult("用户名已存在");
        }
        user = new User();
        user.setEmail(email);
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userDAO.addUser(user);
        return TravelResult.getOkResult("注册成功", getToken(user));
    }

    @Autowired
    private JedisClient jedisClient;
    @Value("${USER_SESSION}")
    private String USER_SESSION;
    @Value("${SESSION_EXPIRE}")
    private Integer SESSION_EXPIRE;

    @Override
    public TravelResult doLogin(String email, String password) {
        User user = userDAO.getUserEmail(email);
        if (user == null || !user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            return TravelResult.getErrorResult("用户名或密码错误");
        }
        return TravelResult.getOkResult("登录成功", getToken(user));
    }

    @Override
    public TravelResult getUserByToken(String token) {
        String json = jedisClient.get(USER_SESSION + ":" + token);
        if (StringUtils.isBlank(json)) {
            return TravelResult.getErrorResult("登录已过期");
        }
        //重置Session的过期时间
        jedisClient.expire(USER_SESSION + ":" + token, SESSION_EXPIRE);
        User user = (User) JsonUtil.getObj(json, User.class);
        return TravelResult.getOkResult("", user);
    }

    @Override
    public TravelResult doLogout(String token) {
        jedisClient.del(USER_SESSION + ":" + token);
        System.out.println(token);
        return TravelResult.getOkResult("退出成功");
    }

    public String getToken(User user) {
        String token = UUID.randomUUID().toString();
        //清空密码
        user.setPassword(null);
        //把用户信息保存到redis，key就是token，value就是用户信息
        jedisClient.set(USER_SESSION + ":" + token, JsonUtil.getJSON(user));
        //设置key的过期时间
        jedisClient.expire(USER_SESSION + ":" + token, SESSION_EXPIRE);
        return token;
    }

}
